<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register | Health Platform</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/css/test.css">
    <link rel="stylesheet" href="/css/auth.css?v=1.0">
</head>
<body>
    <div class="container">
        <div class="logo">
            <h2>Health Platform</h2>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h1>Create Your Account</h1>
                <p>Fill out the form below to get started</p>
            </div>
            
            <div class="card-body">
                <div id="alertBox" class="alert alert-danger" style="display: none;">
                    <p id="alertMessage"></p>
                </div>
                
                <form id="registerForm">
                    <div class="role-selector">
                        <div class="role-option">
                            <input type="radio" id="roleDoctor" name="role" value="DOCTOR" required>
                            <label for="roleDoctor">
                                <i class="fas fa-user-md"></i>
                                <span>Doctor</span>
                            </label>
                        </div>
                        <div class="role-option">
                            <input type="radio" id="rolePatient" name="role" value="PATIENT" checked>
                            <label for="rolePatient">
                                <i class="fas fa-user"></i>
                                <span>Patient</span>
                            </label>
                        </div>
                    </div>
                    
                    <div class="form-grid">
                        <div class="form-group">
                            <i class="fas fa-user form-icon"></i>
                            <input type="text" class="form-control" id="username" name="username" placeholder="Username" required>
                            <small id="usernameError" class="form-text text-danger"></small>
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-id-card form-icon"></i>
                            <input type="text" class="form-control" id="fullName" name="fullName" placeholder="Full Name" required>
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-envelope form-icon"></i>
                            <input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-phone form-icon"></i>
                            <input type="tel" class="form-control" id="phoneNumber" name="phoneNumber" placeholder="Phone Number">
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-lock form-icon"></i>
                            <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
                            <i class="fas fa-eye password-toggle" id="passwordToggle"></i>
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-lock form-icon"></i>
                            <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="Confirm Password" required>
                            <i class="fas fa-eye password-toggle" id="confirmPasswordToggle"></i>
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-venus-mars form-icon"></i>
                            <div class="form-select">
                                <select class="form-control" id="gender" name="gender" required>
                                    <option value="" disabled selected>Select Gender</option>
                                    <option value="MALE">Male</option>
                                    <option value="FEMALE">Female</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <i class="fas fa-calendar form-icon"></i>
                            <input type="date" class="form-control" id="dateOfBirth" name="dateOfBirth" placeholder="Date of Birth">
                        </div>
                        
                        <div class="form-group form-grid-full">
                            <i class="fas fa-info-circle form-icon"></i>
                            <textarea class="form-control" id="bio" name="bio" placeholder="Short bio (optional)" rows="3" style="padding-left: 3rem;"></textarea>
                        </div>
                    </div>
                    
                    <div class="password-requirements">
                        <p>Password must:</p>
                        <div class="requirement" id="req-length">
                            <i class="far fa-circle"></i>
                            <span>Be at least 6 characters long</span>
                        </div>
                        <div class="requirement" id="req-match">
                            <i class="far fa-circle"></i>
                            <span>Passwords match</span>
                        </div>
                    </div>
                    
                    <button type="submit" class="button" id="registerButton" style="margin-top: 1.5rem;">
                        Create Account
                        <i class="fas fa-spinner fa-spin loading-icon" id="loadingIcon"></i>
                    </button>
                </form>
            </div>
            
            <div class="card-footer">
                <p>Already have an account? <a href="/auth/login">Login</a></p>
            </div>
        </div>
    </div>
    
    <script>
        // Global error handler for debugging
        window.addEventListener('error', function(event) {
            console.error('JS Error:', event.error);
            const alertBox = document.getElementById('alertBox');
            const alertMessage = document.getElementById('alertMessage');
            if (alertBox && alertMessage) {
                alertMessage.textContent = 'JavaScript Error: ' + (event.error ? event.error.message : 'Unknown error');
                alertBox.style.display = 'block';
            }
        });
        
        document.addEventListener('DOMContentLoaded', function() {
            const registerForm = document.getElementById('registerForm');
            const registerButton = document.getElementById('registerButton');
            const loadingIcon = document.getElementById('loadingIcon');
            const alertBox = document.getElementById('alertBox');
            const alertMessage = document.getElementById('alertMessage');
            const passwordInput = document.getElementById('password');
            const confirmPasswordInput = document.getElementById('confirmPassword');
            const passwordToggle = document.getElementById('passwordToggle');
            const confirmPasswordToggle = document.getElementById('confirmPasswordToggle');
            const usernameInput = document.getElementById('username');
            const usernameError = document.getElementById('usernameError');
            
            // Password requirement checks
            const reqLength = document.getElementById('req-length');
            const reqMatch = document.getElementById('req-match');
            
            // Toggle password visibility
            passwordToggle.addEventListener('click', function() {
                togglePasswordVisibility(passwordInput, passwordToggle);
            });
            
            confirmPasswordToggle.addEventListener('click', function() {
                togglePasswordVisibility(confirmPasswordInput, confirmPasswordToggle);
            });
            
            function togglePasswordVisibility(input, icon) {
                if (input.type === 'password') {
                    input.type = 'text';
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    input.type = 'password';
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            }
            
            // Check username availability (debounced)
            let usernameCheckTimeout;
            usernameInput.addEventListener('input', function() {
                clearTimeout(usernameCheckTimeout);
                usernameError.textContent = '';
                
                if (usernameInput.value.length >= 3) {
                    usernameCheckTimeout = setTimeout(checkUsernameAvailability, 500);
                }
            });
            
            async function checkUsernameAvailability() {
                try {
                    const response = await fetch(`/api/users/check/username?value=${usernameInput.value}`);
                    const data = await response.json();
                    
                    if (response.ok && data.exists) {
                        usernameError.textContent = 'Username is already taken';
                    }
                } catch (error) {
                    console.error('Error checking username:', error);
                }
            }
            
            // Update password requirements in real time
            function updatePasswordRequirements() {
                // Check length
                if (passwordInput.value.length >= 6) {
                    reqLength.classList.remove('invalid');
                    reqLength.classList.add('valid');
                    reqLength.querySelector('i').classList.remove('far', 'fa-circle');
                    reqLength.querySelector('i').classList.add('fas', 'fa-check-circle');
                } else {
                    reqLength.classList.remove('valid');
                    reqLength.classList.add('invalid');
                    reqLength.querySelector('i').classList.remove('fas', 'fa-check-circle');
                    reqLength.querySelector('i').classList.add('far', 'fa-circle');
                }
                
                // Check if passwords match
                if (passwordInput.value && confirmPasswordInput.value) {
                    if (passwordInput.value === confirmPasswordInput.value) {
                        reqMatch.classList.remove('invalid');
                        reqMatch.classList.add('valid');
                        reqMatch.querySelector('i').classList.remove('far', 'fa-circle');
                        reqMatch.querySelector('i').classList.add('fas', 'fa-check-circle');
                    } else {
                        reqMatch.classList.remove('valid');
                        reqMatch.classList.add('invalid');
                        reqMatch.querySelector('i').classList.remove('fas', 'fa-check-circle');
                        reqMatch.querySelector('i').classList.add('far', 'fa-circle');
                    }
                } else {
                    reqMatch.classList.remove('valid');
                    reqMatch.classList.add('invalid');
                    reqMatch.querySelector('i').classList.remove('fas', 'fa-check-circle');
                    reqMatch.querySelector('i').classList.add('far', 'fa-circle');
                }
            }
            
            passwordInput.addEventListener('input', updatePasswordRequirements);
            confirmPasswordInput.addEventListener('input', updatePasswordRequirements);
            
            // Handle form submission
            registerForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                // Validate passwords match
                if (passwordInput.value !== confirmPasswordInput.value) {
                    alertMessage.textContent = 'Passwords do not match';
                    alertBox.style.display = 'block';
                    return;
                }
                
                // Show loading state
                registerButton.disabled = true;
                loadingIcon.style.display = 'inline-block';
                alertBox.style.display = 'none';
                
                // Format date of birth as ISO string if present
                const dobInput = document.getElementById('dateOfBirth');
                let dateOfBirth = null;
                if (dobInput.value) {
                    dateOfBirth = dobInput.value; // Already in YYYY-MM-DD format
                }
                
                const formData = {
                    username: document.getElementById('username').value,
                    password: document.getElementById('password').value,
                    fullName: document.getElementById('fullName').value,
                    email: document.getElementById('email').value || null,
                    phoneNumber: document.getElementById('phoneNumber').value || null,
                    gender: document.getElementById('gender').value,
                    dateOfBirth: dateOfBirth,
                    bio: document.getElementById('bio').value || "",
                    role: document.querySelector('input[name="role"]:checked').value
                };
                
                console.log('Sending registration data:', formData);
                
                try {
                    const response = await fetch('/auth/register', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(formData),
                    });
                    
                    const responseData = await response.json();
                    console.log('Registration response:', responseData);
                    
                    if (!response.ok) {
                        throw new Error(responseData.message || 'Registration failed');
                    }
                    
                    // Extract user data from the API response - Updated to handle new response format
                    // The server is now returning a different format with user at the top level
                    const userData = responseData.user || responseData;
                    
                    if (!userData) {
                        console.error('Invalid response format:', responseData);
                        throw new Error('Invalid response format from server');
                    }
                    
                    console.log('User data extracted:', userData);
                    
                    // Registration successful and user is automatically logged in with cookies
                    // Store user data for session use
                    sessionStorage.setItem('user', JSON.stringify(userData));
                    
                    // Alert user about successful registration
                    alertBox.classList.remove('alert-danger');
                    alertBox.classList.add('alert-success');
                    alertMessage.textContent = 'Registration successful! Redirecting...';
                    alertBox.style.display = 'block';
                    
                    // Add a small delay to ensure cookies are set before redirecting
                    setTimeout(() => {
                        // Redirect based on user role
                        if (userData.role === 'DOCTOR') {
                            window.location.href = '/page/index';
                        } else if (userData.role === 'PATIENT') {
                            window.location.href = '/page/index';
                        } else {
                            window.location.href = '/dashboard';
                        }
                    }, 1000); // 1 second delay
                    
                } catch (error) {
                    console.error('Registration error:', error);
                    // Show error message
                    alertMessage.textContent = error.message || 'An error occurred during registration. Please try again.';
                    alertBox.style.display = 'block';
                    
                    // Reset loading state
                    registerButton.disabled = false;
                    loadingIcon.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html> 